package com.wanggd.redission.controller;

import com.wanggd.redission.config.DistributedLocker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redisson")
public class AdvMaterialController {
    @Autowired
    private DistributedLocker distributedLocker;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/test")
    public void redissonTest() {
        String key = "redisson_key";
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        boolean isGetLock =  distributedLocker.tryLock(key,TimeUnit.SECONDS,5L,10L); //尝试获取锁，等待5秒，自己获得锁后一直不解锁则10秒后自动解锁
                        if(isGetLock){
                            int stock = Integer.parseInt(redisTemplate.opsForValue().get("goodsStock").toString());
                            if(stock > 0){
                                redisTemplate.opsForValue().set("goodsStock",(stock-1)+"");
                                System.out.println(Thread.currentThread().getName() +",获取到了锁_lockkey:"+key+",剩余stock:"+(stock-1)+"");
                            }else{
                                System.out.println("库存不足");
                            }
                            distributedLocker.unlock(key);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
    }
  }
}
